<template>
	<view v-if="tabs.length" class="tabs" :class="{ flex }" :style="{ background: bgColor || '' }">
		<view
			v-for="item in tabs"
			:key="item.id"
			class="tab-item"
			:class="{ active: item.id == activeTabId }"
			@click="tabClick(item.id)"
		>
			<view class="pos-rel">
				<u-badge
					v-if="showBadge"
					numberType="overflow"
					type="error"
					max="99"
					:value="item.count || 0"
					absolute
					:offset="
						item.count && item.count > 0 && item.count < 10
							? [-5, -16]
							: item.count && item.count >= 10 && item.count <= 99
							? [-5, -22]
							: [-5, -30]
					"
				></u-badge>
				{{ item.name }}
				<template v-if="hasCount">({{ item.count }})</template>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
import type { ZjyTabItem } from "@/types/common"
import { ref, watch, onMounted } from "vue"

interface Props {
	tabs: ZjyTabItem[]
	autoClick: boolean
	activeId: string
	flex: boolean
	hasCount: boolean
	bgColor: string
	showBadge: boolean
}

const props = defineProps<Props>()

const emit = defineEmits(["tabClick"])

const activeTabId = ref<string>(props.activeId)

watch(
	() => props.activeId,
	(id) => {
		activeTabId.value = id
	},
	{ immediate: true }
)

watch(
	() => props.tabs,
	(tabs) => {
		if (tabs.length === 0) return
		if (props.autoClick) {
			const firstTabId = tabs[0]?.id
			if (firstTabId) {
				activeTabId.value = props.activeId || firstTabId
			}
		}
	},
	{ deep: true, immediate: true }
)

const tabClick = (id: string) => {
	activeTabId.value = id
	emit("tabClick", id)
}

onMounted(() => {
	if (props.autoClick && props.tabs.length > 0) {
		const firstTabId = props.tabs[0]?.id
		if (firstTabId) {
			activeTabId.value = props.activeId || firstTabId
		}
	}
})
</script>

<style scoped lang="scss">
.tabs {
	height: 88rpx;
	display: -webkit-box;
	overflow-x: auto;
	overflow-y: hidden;
	font-size: 28rpx;
	color: rgba(0, 0, 0, 0.6);

	&.flex {
		display: flex;

		.tab-item {
			flex: 1;
			padding: 0;
		}
	}

	.tab-item {
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 0 24rpx;
		min-width: 100rpx;
		position: relative;

		&.active {
			color: rgba(0, 0, 0, 0.9);
			font-weight: 600;
			&::after {
				position: absolute;
				content: "";
				width: 44rpx;
				height: 6rpx;
				bottom: 0;
				background: #fee038;
				border-radius: 6rpx;
			}
		}
	}
}
</style>
